package gui;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import kernel.Kernel;

import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ConnectionListener;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.XMPPException;

public class MainUI extends JFrame {
	private static final long serialVersionUID = 1L;
	
	private Kernel _kernel;
	
	private Action _googleTalkLogin, _createChatSession, _rosterViewerAction, _exit;
	
	public MainUI() {
		super("Boodskapper");
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setSize(400, 150);
		this.setIconImage(new IconFactory().getDisconnectedIcon());
		
		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		this.setLocation((screenSize.width - this.getWidth())/2, (screenSize.height - this.getHeight())/2);
		
		this.setKernel(Kernel.getActiveKernel());
		
		JMenuBar menuBar = new JMenuBar();
		JMenu menu = new JMenu("Chat");
		
		JMenuItem item = new JMenuItem(_googleTalkLogin = new CreateGoogleTalkLoginAction());
		menu.add(item);
		
		item = new JMenuItem(_createChatSession = new CreateChatSessionAction());
		_createChatSession.setEnabled(false);
		menu.add(item);
		
		item = new JMenuItem(_rosterViewerAction = new RosterViewerAction());
		_rosterViewerAction.setEnabled(false);
		menu.add(item);
		
		item = new JMenuItem(_exit = new ExitAction());
		menu.add(item);
		
		menuBar.add(menu);
		this.setJMenuBar(menuBar);
		this.setVisible(true);
	}
	
	public void setKernel(Kernel kernel){
		if(_kernel == null || (_kernel != null && _kernel != kernel)){
			_kernel = kernel;
			
			_kernel.addConnectionListener(new ConnectionListener(){
				@Override
				public void connectionClosed() {
					MainUI.this.setTitle("Boodskapper disconnected");
				}

				@Override
				public void connectionClosedOnError(Exception e) {
					MainUI.this.setTitle("Boodskapper disconnected");
				}

				@Override
				public void reconnectingIn(int seconds) {
					MainUI.this.setTitle("Boodskapper reconnecting in "+seconds+"sec...");
				}

				@Override
				public void reconnectionFailed(Exception e) {
					MainUI.this.setTitle("Boodskapper reconnecting failed");
				}

				@Override
				public void reconnectionSuccessful() {
					MainUI.this.setTitle("Boodskapper");
				}});
		}
	}
	
	private void CreateGui(Chat chat){
		UserInput userInput = new UserInput(chat);
		
		this.getContentPane().removeAll();
		this.getContentPane().add(userInput, BorderLayout.CENTER);
		this.pack();
		this.validate();
	}
	
	
	
	
	private class CreateGoogleTalkLoginAction extends AbstractAction {
		private static final long serialVersionUID = 1L;

		public CreateGoogleTalkLoginAction() {
			super("Create Google Talk Login");
		}
		
		@Override
		public void actionPerformed(ActionEvent arg0) {
			GoogleTalkLoginGui dialog = new GoogleTalkLoginGui(MainUI.this, "Google Talk Login...", true);
			try {
				_kernel.createGoogleTalkConnection(dialog.getUsername(), dialog.getPassword());
			} catch (XMPPException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			if(_kernel.getConnection() != null && _kernel.getConnection().isConnected()){
				
				MainUI.this.setIconImage(new IconFactory().getConnectedIcon());
				
				_createChatSession.setEnabled(true);
				_rosterViewerAction.setEnabled(true);
			}
		}
	}
	
	private class CreateChatSessionAction extends AbstractAction {
		private static final long serialVersionUID = 1L;
		private JDialog _dialog;
		private JTextField _buddyUsername;
		
		private JButton _ok;
		
		CreateChatSessionAction(){
			super("Create Chat Session");
		}
		@Override
		public void actionPerformed(ActionEvent e) {
			_dialog = new JDialog(MainUI.this, "Google email address of buddy", true);
			_dialog.setLocation(_dialog.getOwner().getLocation());
			_buddyUsername = new JTextField("Enter Google Email address of buddy here: xxx@gmail.com or xxx@googlemail.com");
			_buddyUsername.addKeyListener(new KeyAdapter(){
				@Override
				public void keyReleased(KeyEvent e) {
					if (e.getKeyCode() == KeyEvent.VK_ENTER) {
						e.consume();
						_ok.doClick();
					}
				}
			});
			_dialog.getContentPane().add(_buddyUsername, BorderLayout.CENTER);
			_ok = new JButton("OK");
			_ok.addActionListener(new ActionListener(){
				@Override
				public void actionPerformed(ActionEvent e) {
					if (_kernel.getConnection() != null && _kernel.getConnection().isConnected()) {
						String user = _buddyUsername.getText().trim();
						Chat chat = _kernel.getChat(user);
						if(chat != null){
							_dialog.setVisible(false);
							CreateGui(chat);
						}
					}
					else{
						JOptionPane.showMessageDialog(MainUI.this, "The connection was null", "Connection Error", JOptionPane.ERROR_MESSAGE);
					}
				}
			});
			_dialog.getContentPane().add(_ok, BorderLayout.SOUTH);
			
			RosterViewer rosterViewer = new RosterViewer(_kernel.getConnection().getRoster());
			rosterViewer.addSelectionListener(new ListSelectionListener(){
				@Override
				public void valueChanged(ListSelectionEvent e) {
					if(e.getValueIsAdjusting() == false)
					{
						if (e.getSource() instanceof JList) {
							JList list = (JList)e.getSource();
							if(list != null)
							{
								if (list.getSelectedValue() instanceof RosterEntry) {
									RosterEntry entry = (RosterEntry) list.getSelectedValue();
									_buddyUsername.setText(entry.getUser());
								}
							}
						}
					}
				}});
			_dialog.getContentPane().add(rosterViewer, BorderLayout.NORTH);
			
			
			_dialog.pack();
			_dialog.setVisible(true);
		}
	}
	
	private class RosterViewerAction extends AbstractAction{
		private static final long serialVersionUID = 1L;

		RosterViewerAction() {
			super("Roster");
		}

		@Override
		public void actionPerformed(ActionEvent arg0) {
			JDialog dialog = new JDialog(MainUI.this, "Roster viewer...", false);
			dialog.getContentPane().add(new RosterViewer(_kernel.getConnection().getRoster()));
			dialog.setVisible(true);
			dialog.pack();
		}
	}
	
	private class ExitAction extends AbstractAction{
		private static final long serialVersionUID = 1L;
		public ExitAction() {
			super("Exit");
		}
		@Override
		public void actionPerformed(ActionEvent e) {
			if(_kernel.getConnection() != null && _kernel.getConnection().isConnected())
				_kernel.getConnection().disconnect();
			
			MainUI.this.setVisible(false);
			MainUI.this.dispose();
			System.exit(0);
		}
	}
}
